<?php

namespace App\Http\Controllers;


use App\Models\Configs;
use App\Models\SystemUsers;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;

class SystemController extends Controller
{

    public function config()
    {
        if ($this->isPost()) {
            $fields = $this->request->all();
            unset($fields['_token']);
            foreach ($fields as $name => $value) {
                Configs::updateOrCreate(['name' => $name], [
                    'value' => $value
                ]);
                Configs::clean($name);
            }
            return $this->setJson(0, '保存成功');
        }
        $title = '系统配置';
        $item  = Configs::pluck('value', 'name');
        return view('system.config', compact('title', 'item'));
    }

    public function back_db()
    {
        $title = '数据库备份管理';
        if ($this->isPost()) {
            $nodes = self::getTree(sgConfig('back_db_path'), false);
            return $this->setJson(0, 'ok', $nodes);
        }
        return view('system.db', compact('title'));
    }

    public function back_site()
    {
        $title = '站点备份管理';
        if ($this->isPost()) {
            $nodes = self::getTree(sgConfig('back_site_path'), false);
            return $this->setJson(0, 'ok', $nodes);
        }
        return view('system.site', compact('title'));
    }

    /**
     * 下载
     */
    public function download()
    {
        $md5  = $this->request->input('md5', '');
        $file = Cache::get($md5);
        if (file_exists($file)) {
            sg_download($file);
        } else {
            return '文件不存在';
        }
    }

    /**
     * 获取目录下的结构
     * @param $data_dir string 必须以/结尾
     * @param $spread bool 是否展开
     * @return array
     */
    public static function getTree($data_dir, $spread = false)
    {
        $list = glob($data_dir . '*');
        rsort($list);
        $tree = [];
        if ($list) {
            foreach ($list as $child_dir) {
                $tmp             = [];
                $name            = pathinfo($child_dir, PATHINFO_BASENAME);
                $tmp['name']     = date('Y年m月d日', strtotime($name));
                $tmp['spread']   = $spread;
                $tmp['children'] = [];
                $ls              = glob($child_dir . '/*');
                if ($ls) {
                    $total = 0;
                    foreach ($ls as $file) {
                        if (is_file($file)) {
                            $size        = filesize($file);
                            $total       += $size;
                            $size_format = size2mb($size);
                            $md5         = md5($file);
                            Cache::put($md5, $file, Carbon::now()->addDay(1));
                            $tmp['children'][] = [
                                'name'   => pathinfo($file, PATHINFO_BASENAME) . '(' . $size_format . ')',
                                'spread' => $spread,
                                'md5'    => $md5,
                            ];
                        }
                    }
                    $tmp['name'] .= '(' . size2mb($total) . ')';
                }
                $tree[] = $tmp;
            }
        }
        return $tree;
    }

    /**
     * 管理员列表
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function lists()
    {
        if ($this->isPost()) {
            $name  = $this->request->input('name', '');
            $where = '1';
            if (!empty($name)) {
                $where .= ' and name=' . "'{$name}'";
            }
            $data = SystemUsers::orderBy('id', 'desc')
                ->whereRaw($where)
                ->paginate($this->request->input('limit'));
            $i    = 1;
            foreach ($data as $item) {
                $item->sid            = $i;
                $item->last_format    = Carbon::parse($item->last_at)->diffForHumans();
                $item->created_format = Carbon::parse($item->created_at)->diffForHumans();
                $i++;
            }
            $list    = $data->toArray();
            $content = [
                'code'  => 0,
                'msg'   => '',
                'count' => $list['total'],
                'data'  => $list['data'],
            ];
            return $content;
        }
        $title = '管理员列表';
        return view('system.list', compact('title', 'data'));
    }

    public function info()
    {
        return view('system.info');
    }

    /**
     * 登陆
     * @return $this|Response|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function login()
    {
        if ($this->isPost()) {
            $username = $this->request->input('username');
            $password = $this->request->input('password');
            $captcha  = $this->request->input('captcha');
            if (empty($username)) {
                return $this->setJson(10, '请输入用户名称');
            }
            if (empty($password)) {
                return $this->setJson(10, '请输入用户密码');
            }
            if (empty($captcha)) {
                return $this->setJson(10, '请输入验证码');
            }
            if (!captcha_check($captcha)) {
                return $this->setJson(20, '验证输入错误');
            }
            //验证用户
            $user = SystemUsers::where('name', $username)->first();
            if (!$user) {
                return $this->setJson(10, '用户或密码不存在');
            }
            if ($user->is_use == 0) {
                return $this->setJson(11, '已被管理员禁止登陆');
            }
            if (!Hash::check($password, $user->password)) {
                return $this->setJson(10, '用户或密码不存在!');
            }
            $user->login_count++;
            $user->last_ip = $this->request->getClientIp();
            $user->last_at = Carbon::now();
            $bool          = $user->save();
            if ($bool) {
                session(['user_id' => $user->id]);
                return $this->setJson(0, 'ok', route('home'));
            }
        }
        return view('system.login');
    }

    /**
     * 编辑和添加
     *
     * @return $this|Response|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit()
    {
        $id    = $this->request->input('id', 0);
        $name  = $this->request->input('name', '');
        $pass  = $this->request->input('password', '');
        $pass2 = $this->request->input('password2', '');
        $user  = null;
        if ($id > 0) {
            $title = '编辑管理员';
            $user  = SystemUsers::find($id);
            if ($this->isPost()) {
                if (empty($name)) {
                    return $this->setJson(10, '用户名不能为空');
                }
                $user->name = $name;
                if (!empty($pass2) || !empty($pass)) {
                    if ($pass != $pass2) {
                        return $this->setJson(12, '两次输入密码不一致');
                    }
                    $user->password = bcrypt($pass);
                }
                $bool = $user->save();
                if ($bool) {
                    return $this->setJson(0, '修改成功', route('system.list'));
                }
                return $this->setJson(20, '修改失败');
            }
        } else {
            if ($this->isPost()) {
                if (empty($name)) {
                    return $this->setJson(10, '用户名不能为空');
                }
                if (empty($pass) || empty($pass2)) {
                    return $this->setJson(11, '密码不能为空');
                }
                if ($pass != $pass2) {
                    return $this->setJson(12, '两次输入密码不一致');
                }
                if (strlen($pass2) < 6) {
                    return $this->setJson(13, '密码不能少于6位');
                }
                $secret_pass = bcrypt($pass);
                $bool        = SystemUsers::create([
                    'name'     => $name,
                    'password' => $secret_pass,
                    'is_use'   => 1,
                ]);
                if ($bool) {
                    return $this->setJson(0, '注册成功', route('system.list'));
                }
                return $this->setJson(14, '注册失败');
            }
            $title = '添加管理员';
        }
        return view('system.edit', compact('title', 'user'));
    }

    /**
     * 删除数据
     * @return $this|Response
     */
    public function del()
    {
        $id   = $this->request->input('id', 0);
        $item = SystemUsers::find($id);
        if (!$item) {
            return $this->setJson(10, '数据不存在');
        }
        if ($item->id == 1) {
            return $this->setJson(12, '管理员帐号不允许操作');
        }
        $bool = $item->delete();
        if ($bool) {
            return $this->setJson(0, '操作成功');
        }
        return $this->setJson(400, '异常');
    }

    public function change()
    {
        $id     = $this->request->input('id', 0);
        $status = $this->request->input('value', 0);
        $item   = SystemUsers::find($id);
        if (!$item) {
            return $this->setJson(10, '数据不存在');
        }
        if (!in_array($status, [0, 1])) {
            return $this->setJson(11, '状态值异常');
        }
        if ($item->id == 1) {
            return $this->setJson(12, '管理员帐号不允许操作');
        }
        $item->is_use = $status;
        $bool         = $item->save();
        if ($bool) {
            return $this->setJson(0, '操作成功');
        }
        return $this->setJson(400, '异常');
    }
}
